package cn.mifengkong.appcommon.moxie;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.mifengkong.frtools.system.timer.FRTimer;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRToast;
import com.moxie.client.manager.MoxieCallBack;
import com.moxie.client.manager.MoxieCallBackData;
import com.moxie.client.manager.MoxieContext;
import com.moxie.client.manager.MoxieSDK;
import com.moxie.client.manager.MoxieSDKRunMode;
import com.moxie.client.model.MxLoginCustom;
import com.moxie.client.model.MxParam;
import com.moxie.client.model.TitleParams;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import cn.mifengkong.appcommon.constant.AppCommonConstant;

/**
 * Created by jack on 2017/11/28
 */

public abstract class FRMoXieManager {

    protected boolean mIsRunning = false;
    private String materialCode;

    protected Activity activity;
    private MxParam mMxParam;
    private String email;

    private FRTimer frTimer;
    private FrMoxieCallBack mFrMoxieCallBack;

    private FRMoXieManager() {

    }

    protected FRMoXieManager(Activity activity) {
        this.activity = activity;
        mFrMoxieCallBack = new FrMoxieCallBack();
        frTimer = new FRTimer();
    }

    protected void initMoXie(String function, Map<String, Object> hashMap) {
        mMxParam = initMxParam(function, hashMap);
    }

    protected void initOnlineBankingMoXie(String function, Map<String, Object> hashMap) {
        mMxParam = initOnlineBankingMxParam(function, hashMap);
    }

    public void startRun() {
        if (null == frTimer) {
            frTimer = new FRTimer();
        }
        if (!mIsRunning) {
            run();
        }
    }

    public void startRun(boolean isRunning) {
        if (null == frTimer) {
            frTimer = new FRTimer();
        }
        mIsRunning = isRunning;
        if (!mIsRunning) {
            run();
        }
    }

    private void run() {
        if (null != frTimer) {
            frTimer.schedule(3000, 3000, new Runnable() {
                @Override
                public void run() {
                    looperMethod(email);
                    mIsRunning = true;
                }
            });
        }
    }

    protected abstract void looperMethod(String email);

    protected void startMoxieActivity() {
        startMoxieActivity(mMxParam);
    }

    protected void startMoxieActivity(MxParam mxParam) {
        MoxieSDK.getInstance().start(activity, mxParam, mFrMoxieCallBack);
    }

    /**
     * 支持静默更新的魔蝎调用方法
     *
     * @param mxParam
     * @param moxieSDKRunMode
     */
    protected void startMoxieActivity(MxParam mxParam, MoxieSDKRunMode moxieSDKRunMode) {
        MoxieSDK.getInstance().startInMode(activity, moxieSDKRunMode, mxParam, mFrMoxieCallBack);
    }

    protected abstract void successReturn(String email);

    protected abstract void verifyCate(String materialCode);

    public void onDestroy() {
        //用来清理数据或解除引用
        MoxieSDK.getInstance().clear();
    }

    public void onStop() {
        if (null != frTimer) {
            frTimer.stop();
            mIsRunning = false;
            frTimer = null;
        }
    }

    /**
     * 初始化魔蝎SDK的所需要的参数
     * <p>
     * 除去网银以外的魔蝎验证
     *
     * @return
     */
    protected MxParam initMxParam(String function, Map<String, Object> hashMap) {
        MxParam mxParam = initBaseMxParam(hashMap, function);
        mxParam.setTaskType(function);
        //需求:如果是运营商验证，需要该title为手机号验证,并且是将用户的身份证号和姓名也帮用户填好了
        currentTaskIsCarrier(function, hashMap, mxParam);
        return mxParam;
    }

    /**
     * 当前的任务是否为运营商验证
     *
     * @param function
     * @param hashMap
     * @param mxParam
     */
    private boolean currentTaskIsCarrier(String function, Map<String, Object> hashMap, MxParam mxParam) {
        if (MxParam.PARAM_TASK_CARRIER.equals(function)) {
            MxLoginCustom loginCustom = new MxLoginCustom();
            HashMap<String, Object> extendParam = new HashMap<>();
            // 身份证
            extendParam.put("idcard", hashMap.get(AppCommonConstant.ID_CARD));
            // 姓名
            extendParam.put("name", hashMap.get(AppCommonConstant.NAME));
            //手机号
//            extendParam.put("phone", hashMap.get(AppCommonConstant.CARRIER_PHONE));
            // 是否允许用户修改
            loginCustom.setEditable(MxParam.PARAM_COMMON_NO);
            loginCustom.setLoginParams(extendParam);
            mxParam.setLoginCustom(loginCustom);
            return true;
        }
        return false;
    }

    /**
     * 默认参数
     *
     * @param hashMap
     * @return
     */
    private MxParam initBaseMxParam(Map<String, Object> hashMap) {
        return initBaseMxParam(hashMap, null);
    }

    /**
     * 默认参数带taskname
     *
     * @param hashMap
     * @param taskName
     * @return
     */
    @NonNull
    private MxParam initBaseMxParam(Map<String, Object> hashMap, String taskName) {
        MxParam mxParam = new MxParam();
        mxParam.setUserId((String) hashMap.get(AppCommonConstant.USER_ID));
        mxParam.setApiKey(AppCommonConstant.MAPIKEY);
        // SDK里显示的用户使用协议
        mxParam.setAgreementUrl(AppCommonConstant.MAGREEMENTURL);
        mxParam.setThemeColor((String) hashMap.get(AppCommonConstant.MOXIE_THEME_COLOR));
        TitleParams.Builder builder = new TitleParams.Builder();
        //标题字体颜色
        builder.titleColor((Integer) hashMap.get(AppCommonConstant.MOXIE_TEXT_COLOR))
                //title背景色
                .backgroundColor((Integer) hashMap.get(AppCommonConstant.MOXIE_BANNER_BG))
                //是否支持沉浸式
                .immersedEnable(true)
                //title返回按钮旁边的文字（关闭）的颜色
                .leftTextColor((Integer) hashMap.get(AppCommonConstant.MOXIE_TEXT_COLOR))
                //title返回按钮旁边的文字，一般为关闭
                .leftText("关闭");
        if (null != hashMap.get(AppCommonConstant.MOXIE_LEFT_RES)) {
            builder.leftNormalImgResId((Integer) hashMap.get(AppCommonConstant.MOXIE_LEFT_RES));
        }
        if (null != hashMap.get(AppCommonConstant.MOXIE_RIGHT_RES)) {
            builder.rightNormalImgResId((Integer) hashMap.get(AppCommonConstant.MOXIE_RIGHT_RES));
        }
        if (null != hashMap.get(AppCommonConstant.MOXIE_IMMERSED_ENABLE)) {
            builder.immersedEnable((Boolean) hashMap.get(AppCommonConstant.MOXIE_IMMERSED_ENABLE));
        }
        if (MxParam.PARAM_TASK_CARRIER.equals(taskName)) {
            builder.title("手机号验证");
        }
        TitleParams titleParams = builder.build();
        mxParam.setTitleParams(titleParams);
        return mxParam;
    }


    /**
     * 初始化魔蝎SDK的所需要的参数
     * <p>
     * 主要是给网银使用的
     *
     * @return
     */
    protected MxParam initOnlineBankingMxParam(String itemCode, Map<String, Object> hashMap) {
        MxParam mxParam = initBaseMxParam(hashMap);
        mxParam.setQuitOnFail(MxParam.PARAM_COMMON_YES);
        mxParam.setTaskType(MxParam.PARAM_TASK_ONLINEBANK);
        // ⾃定义参数
        MxLoginCustom loginCustom = new MxLoginCustom();
        // 1.信⽤卡
        loginCustom.setLoginType(MxLoginCustom.LOGIN_TYPE_V_CREDITCARD);
        // 2.直达指定的银⾏
        loginCustom.setLoginCode(itemCode);
        mxParam.setLoginCustom(loginCustom);
        return mxParam;
    }

    /**
     * 跳转到指定的邮箱页面
     *
     * @param jumpEmail
     */
    protected void setEmailLoginInfo(String jumpEmail) {
        if (!TextUtils.isEmpty(jumpEmail) && jumpEmail.contains("@")) {
            String mailName = jumpEmail.substring(0, jumpEmail.indexOf("@"));
            String mailCode = jumpEmail.substring(jumpEmail.indexOf("@") + 1);
            HashMap<String, Object> loginParams = new HashMap<>();
            loginParams.put("username", mailName);
            mMxParam.setLoginCustom(new MxLoginCustom()
                    .setLoginCode(mailCode)
                    .setLoginParams(loginParams));

        }
    }

    /**
     * 初始化魔蝎SDK的所需要的参数（邮箱）
     * <p>
     *
     * @return
     */
    public MxParam initSpecificMailMxParamWithPassword(String username, String password, String sepwd, String host, Map<String, Object> hashMap) {
        MxParam mxParam = initBaseMxParam(hashMap);
        mxParam.setQuitOnFail(MxParam.PARAM_COMMON_YES);
        MxLoginCustom mxLoginCustom = new MxLoginCustom();
        HashMap<String, Object> loginCustom = new HashMap<>();
        loginCustom.put("username", username);
        loginCustom.put("password", password);
        loginCustom.put("sepwd", sepwd); //独立密码，目前仅支持qq邮箱
        //指定要登录的邮箱代号，格式如qq.com, sohu.com
        mxLoginCustom.setLoginCode(host).setLoginParams(loginCustom);
        mxParam.setLoginCustom(mxLoginCustom);
        mxParam.setTaskType(MxParam.PARAM_TASK_MAIL);
        return mxParam;
    }

    /**
     * 初始化魔蝎SDK的所需要的参数
     * <p>
     *
     * @return
     */
    public MxParam initSpecificMailMxParam(String host, Map<String, Object> hashMap) {
        return initSpecificMailMxParamWithPassword("", "", "", host, hashMap);
    }

    public class FrMoxieCallBack extends MoxieCallBack {
        @Override
        public boolean callback(MoxieContext moxieContext, MoxieCallBackData moxieCallBackData) {
            /**
             *  MoxieCallBackData的格式如下：
             *  1.1.没有进行账单导入(后台没有通知)
             *      "code" : MxParam.ResultCode.IMPORT_UNSTART, "taskType" : "mail", "searchId" : "", "taskId" : "", "message" : "", "account" : ""
             *  1.2.平台方服务问题(后台没有通知)
             *      "code" : MxParam.ResultCode.THIRD_PARTY_SERVER_ERROR, "taskType" : "mail", "searchId" : "", "taskId" : "", "message" : "", "account" : "xxx"
             *  1.3.魔蝎数据服务异常(后台没有通知)
             *      "code" : MxParam.ResultCode.MOXIE_SERVER_ERROR, "taskType" : "mail", "searchId" : "", "taskId" : "", "message" : "", "account" : "xxx"
             *  1.4.用户输入出错（密码、验证码等输错且未继续输入）
             *      "code" : MxParam.ResultCode.USER_INPUT_ERROR, "taskType" : "mail", "searchId" : "", "taskId" : "", "message" : "密码错误", "account" : "xxx"
             *  2.账单导入失败(后台有通知)
             *      "code" : MxParam.ResultCode.IMPORT_FAIL, "taskType" : "mail", "searchId" : "3550622685459407187", "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx"
             *  3.账单导入成功(后台有通知)
             *      "code" : MxParam.ResultCode.IMPORT_SUCCESS, "taskType" : "mail", "searchId" : "3550622685459407187", "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx"
             *  4.账单导入中(后台有通知)
             *      "code" : MxParam.ResultCode.IMPORTING, "taskType" : "mail", "searchId" : "3550622685459407187", "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx"
             */
            if (moxieCallBackData != null) {
                FRLog.e("jiang", moxieCallBackData.getCode() + "--");
                switch (moxieCallBackData.getCode()) {
                    /**
                     * 如果用户正在导入魔蝎SDK会出现这个情况，如需获取最终状态请轮询贵方后台接口
                     * 魔蝎后台会向贵方后台推送Task通知和Bill通知
                     * Task通知：登录成功/登录失败
                     * Bill通知：账单通知
                     */
                    case MxParam.ResultCode.IMPORTING:
                    case MxParam.ResultCode.IMPORT_UNSTART:
//                            showDialog(moxieContext);
                        EventBus.getDefault().post(new ImportTaskCancelEvent(true));
                        return false;
                    case MxParam.ResultCode.THIRD_PARTY_SERVER_ERROR:
                        FRToast.showToastSafe("导入失败(平台方服务问题)");
                        return false;
                    case MxParam.ResultCode.MOXIE_SERVER_ERROR:
                        FRToast.showToastSafe("导入失败(魔蝎数据服务异常)");
                        return false;
                    case MxParam.ResultCode.USER_INPUT_ERROR:
                        FRToast.showToastSafe("导入失败(" + moxieCallBackData.getMessage() + ")");
                        return false;
                    case MxParam.ResultCode.IMPORT_FAIL:
                        FRToast.showToastSafe("导入失败");
                        return false;
                    case MxParam.ResultCode.IMPORT_SUCCESS:
                        //根据taskType进行对应的处理
                        switch (moxieCallBackData.getTaskType()) {
                            case MxParam.PARAM_TASK_CARRIER:
                                //运营商导入
                                materialCode = "operator_verify";
                                break;
                            case MxParam.PARAM_TASK_ZHENGXIN:
                                //征信导入
                                materialCode = "personal_credit";
                                break;
                            case MxParam.PARAM_TASK_TAOBAO:
                                materialCode = "taobao";
                                break;
                            case MxParam.PARAM_TASK_ONLINEBANK:
                                //网银
                                materialCode = "e_bank";
                                break;
                            case MxParam.PARAM_TASK_EMAIL:
                                //邮箱
                                materialCode = "credit_bill";
                                email = moxieCallBackData.getAccount();
                                break;
                            case MxParam.PARAM_TASK_ALIPAY:
                                //支付宝
                                materialCode = "alipay";
                                break;
                            case MxParam.PARAM_TASK_JINGDONG:
                                //京东
                                materialCode = "jd";
                                break;
                            case MxParam.PARAM_TASK_SECURITY:
                                //社保
                                materialCode = "shebao";
                                break;
                            case MxParam.PARAM_TASK_LIFE_INSURANCE:
                                //寿险
                                materialCode = "life_insurance";
                                break;
                            default:
                                break;

                        }
                        moxieContext.finish();
                        successReturn(email);
                        startRun();
                        verifyCate(materialCode);
                        return true;
                    default:
                        break;
                }
            }
            return false;
        }
    }


}
